from django.db.models import Q
from django.shortcuts import render
from django.http import JsonResponse
import json
# Create your views here.
from staff.models import Staff
import openpyxl

import uuid
import hashlib
import os
# 导入Setting
from django.conf import settings


def index(request):
    try:
        student_obj=Staff.objects.all().values()
        students=list(student_obj)
        #print(students)
        return JsonResponse({"code":1,"data":students})
    except Exception as e:
        return JsonResponse({"code":0,"msg":str(e)})
    # return render(request,'index.html')

def query_staff(request):

    data=json.loads(request.body.decode('utf-8'))
    #print(data)
    try:
        obj_students = Staff.objects.filter(Q(sno__icontains=data['inputstr']) | Q(sname__icontains=data['inputstr'])|
                                                Q(gender__icontains=data['inputstr']) | Q(mobile__icontains=data['inputstr'])|
                                              Q(email__icontains=data['inputstr']) | Q(address__icontains=data['inputstr'])).values()
        students = list(obj_students)
        #print(students)
        return JsonResponse({"code":1,"data":students})
    except Exception as e:
        return JsonResponse({"code":0,"msg":"获取学生信息异常"+str(e)})

def is_exist_sno(request):
    data=json.loads(request.body.decode("utf-8"))
    try:
        obj_student=Staff.objects.filter(sno=data['sno'])
        if obj_student.count()==0:
            return JsonResponse({'code':1,'exist':False})
        else:
            return JsonResponse({'code':1,'exist':True})
    except Exception as e:
        return JsonResponse({'code':0,'msg':'校验学号失败，具体原因：'+str(e)})

def add_stff(request):
    data=json.loads(request.body.decode("utf-8"))
    print("****")
    print(data)
    print(type(data))
    try:
        student = Staff(sno=data["sno"], sname=data["sname"], gender=data["gender"], birthday=data["birthday"],
                          mobile=data["mobile"], email=data["email"], address=data["address"],image=data["image"])
        student.save()

        students_get=Staff.objects.all().values()
        students=list(students_get)
        return  JsonResponse({"code":1,"data":students})

    except Exception as e:
        return JsonResponse({"code":1,"msg":"添加学生信息失败"+str(e)})










